//
//  JOKEViewController.m
//  NEWS
//
//  Created by lanou on 16/4/9.
//  Copyright © 2016年 孙金龙. All rights reserved.
//

#import "JOKEViewController.h"
#import "JOKECell.h"
#import "RequestManager.h"
#import "JOKEModel.h"
@interface JOKEViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *modelArray;
@end

@implementation JOKEViewController

- (void)request
{
    [RequestManager requestWithUrl:@"http://s.budejie.com/topic/list/zuixin/29/baisishequ-iphone-3.9/0-20.json" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *list = dic[@"list"];
        _modelArray = [NSMutableArray array];
        for (NSDictionary *modelDic in list)
        {
            JOKEModel *model = [[JOKEModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [model setValuesForKeysWithDictionary:modelDic[@"u"]];
            [_modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"请求出错");
    } requestType:RequestGte];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self request];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, KWidth, KHeight) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate  = self;
    [_tableView registerClass:[JOKECell class] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:_tableView];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JOKECell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    JOKEModel *model = _modelArray[indexPath.row];
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JOKEModel *model = _modelArray[indexPath.row];
    return [JOKECell HeightForCellWith:model];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
